package main

import (
	"fmt"
	"mcp-clarification-service/internal/config"
	"mcp-clarification-service/internal/gui"
	"mcp-clarification-service/internal/httpserver"
	"mcp-clarification-service/internal/server"
	"mcp-clarification-service/pkg/logger"
	"os"
)

func main() {
	if len(os.Args) < 2 {
		printUsage()
		os.Exit(1)
	}

	command := os.Args[1]

	switch command {
	case "start-mcp-server":
		startMCPServer()
	case "start-gui-server":
		startGUIServer()
	case "version":
		printVersion()
	case "help", "--help", "-h":
		printUsage()
	default:
		fmt.Fprintf(os.Stderr, "Unknown command: %s\n\n", command)
		printUsage()
		os.Exit(1)
	}
}

func printUsage() {
	fmt.Println("MCP Clarification Service")
	fmt.Println()
	fmt.Println("Usage:")
	fmt.Println("  clarification start-mcp-server    Start MCP server (auto-starts GUI if needed)")
	fmt.Println("  clarification start-gui-server    Start GUI server only")
	fmt.Println("  clarification version             Show version information")
	fmt.Println("  clarification help                Show this help message")
}

func printVersion() {
	fmt.Println("MCP Clarification Service v1.0.0")
}


func startMCPServer() {
	// 加载配置
	cfg, err := loadConfig()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to load config: %v\n", err)
		os.Exit(1)
	}

	// 创建日志记录器
	log := logger.New(cfg.Defaults.LogLevel)

	// 创建并启动MCP服务器
	srv := server.NewMCPServer(cfg, log)
	if err := srv.Start(); err != nil {
		log.Error("Server error: %v", err)
		os.Exit(1)
	}
}

func startGUIServer() {
	// 加载配置
	cfg, err := loadConfig()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to load config: %v\n", err)
		os.Exit(1)
	}

	// 创建日志记录器
	log := logger.New(cfg.Defaults.LogLevel)

	// 创建Fyne GUI管理器
	guiManager := gui.NewManager(&cfg.GUI)

	// 创建并启动HTTP服务器
	srv := httpserver.NewServer(cfg.GUI.Port, guiManager, log)
	if err := srv.Start(); err != nil {
		log.Error("Server error: %v", err)
		os.Exit(1)
	}
}

func loadConfig() (*config.Config, error) {
	// 尝试从文件加载
	if _, err := os.Stat("config.json"); err == nil {
		return config.LoadConfig("config.json")
	}

	// 使用默认配置
	return config.DefaultConfig(), nil
}
